package com.qianfeng.demo19_springboot.controller;


import com.qianfeng.demo19_springboot.util.JsonResultVO;
import com.qianfeng.demo19_springboot.util.UserInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class AuthController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 登录服务
     *
     */
    @RequestMapping("/login")
    @ResponseBody
    public JsonResultVO login(UserInfo userInfo){

        JsonResultVO jsonResultVO = new JsonResultVO();

        //登录的业务逻辑
        //访问数据库
        if ("admin".equals(userInfo.getUsername()) && "123456".equals(userInfo.getPassword())) {
            //登录成功
            //将用户信息保存到Redis中
            Md5Hash md5Hash = new Md5Hash();
            String tokenStr = userInfo.getUsername() + userInfo.getPassword() + System.currentTimeMillis();
            md5Hash.setBytes(tokenStr.getBytes());
            // token是暴露给用户的
            String token = md5Hash.toHex();
            //登录成功之后的用户信息保存到Redis中
            redisTemplate.boundValueOps(token).set(userInfo.getUsername(),30, TimeUnit.MINUTES);
            jsonResultVO.setMsg(token);
            jsonResultVO.setCode(1);
            return jsonResultVO;
        }

        jsonResultVO.setCode(0);
        return jsonResultVO;
    }

    /***
     * 通过Token进行鉴权
     * @param token
     * @return
     */
    @RequestMapping("/auth")
    public JsonResultVO auth(String token){

        JsonResultVO jsonResultVO = new JsonResultVO();
        //通过token在redis中查询是否有用户信息
        String userInfo = redisTemplate.boundValueOps(token).get();
        if (userInfo == null || "".equals(userInfo.trim())){
            jsonResultVO.setCode(0);
            return jsonResultVO;
        }

        jsonResultVO.setCode(1);
        return jsonResultVO;

    }


}
